package com.example.demo.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.Result;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/auth")
public class UserAuth {
    @Resource
    private UserService userService;



//    @PostMapping("/register")
//    public Result save(@RequestBody User user) {
//        userService.save(user);
//        return Result.success();
//    }
@PostMapping("/register")
public ResponseEntity<Map<String, Object>> register(@RequestBody Map<String, Object> request) {
    try {
        String phoneNumber = (String) request.get("phone_number");
        String validCode = (String) request.get("valid_code");
        String password = (String) request.get("password");
        String passwordConfirm = (String) request.get("password_confirm");
        
        // 验证必填字段
        if (phoneNumber == null || phoneNumber.trim().isEmpty()) {
            return ResponseEntity.ok(Map.of(
                    "success", false,
                    "message", "手机号不能为空"
            ));
        }
        if (validCode == null || validCode.trim().isEmpty()) {
            return ResponseEntity.ok(Map.of(
                    "success", false,
                    "message", "验证码不能为空"
            ));
        }
        if (password == null || password.trim().isEmpty()) {
            return ResponseEntity.ok(Map.of(
                    "success", false,
                    "message", "密码不能为空"
            ));
        }
        if (passwordConfirm == null || passwordConfirm.trim().isEmpty()) {
            return ResponseEntity.ok(Map.of(
                    "success", false,
                    "message", "确认密码不能为空"
            ));
        }
        
        // 验证密码是否一致
        if (!password.equals(passwordConfirm)) {
            return ResponseEntity.ok(Map.of(
                    "success", false,
                    "message", "两次密码输入不一致"
            ));
        }
        
        // 检查手机号是否已存在
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhoneNumber, Long.parseLong(phoneNumber));
        User existingUser = userService.getOne(queryWrapper);
        if (existingUser != null) {
            return ResponseEntity.ok(Map.of(
                    "success", false,
                    "message", "该手机号已被注册"
            ));
        }
        
        // 创建用户对象
        User user = new User();
        user.setPhoneNumber(Long.parseLong(phoneNumber));
        user.setPassword(password);
        user.setPasswordConfirm(passwordConfirm);
        user.setValidCode(validCode);
        user.setAccount(phoneNumber); // 使用手机号作为账号
        
        // 保存用户到数据库
        boolean saved = userService.save(user);
        
        if (saved) {
            // 注册成功后自动登录，使用Sa-Token生成token
            StpUtil.login(user.getId());
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
            
            return ResponseEntity.ok(Map.of(
                    "success", true,
                    "message", "注册成功",
                    "token", tokenInfo.getTokenValue()
            ));
        } else {
            return ResponseEntity.ok(Map.of(
                    "success", false,
                    "message", "注册失败"
            ));
        }
    } catch (NumberFormatException e) {
        return ResponseEntity.ok(Map.of(
                "success", false,
                "message", "手机号格式不正确"
        ));
    } catch (Exception e) {
        return ResponseEntity.ok(Map.of(
                "success", false,
                "message", "注册失败: " + e.getMessage()
        ));
    }
}

@PostMapping("/login")
public ResponseEntity<Map<String, Object>> login(@RequestBody Map<String, Object> request) {
    try {
        String account = request.get("account") == null ? null : String.valueOf(request.get("account")).trim();
        String phoneFromBody = request.get("phone_number") == null ? null : String.valueOf(request.get("phone_number")).trim();
        String password = request.get("password") == null ? null : String.valueOf(request.get("password")).trim();
        
        // 验证必填字段
        if ((account == null || account.isEmpty()) && (phoneFromBody == null || phoneFromBody.isEmpty())) {
            return ResponseEntity.ok(Map.of(
                    "success", false,
                    "message", "账号或手机号不能为空"
            ));
        }
        if (password == null || password.isEmpty()) {
            return ResponseEntity.ok(Map.of(
                    "success", false,
                    "message", "密码不能为空"
            ));
        }
        
        // 根据账号或手机号与密码查询用户
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPassword, password)
                .and(w -> {
                    boolean added = false;
                    if (account != null && !account.isEmpty()) {
                        w.eq(User::getAccount, account);
                        added = true;
                    }
                    if (phoneFromBody != null && !phoneFromBody.isEmpty()) {
                        try {
                            Long phoneNumber = Long.parseLong(phoneFromBody);
                            if (added) {
                                w.or().eq(User::getPhoneNumber, phoneNumber);
                            } else {
                                w.eq(User::getPhoneNumber, phoneNumber);
                            }
                        } catch (NumberFormatException ignored) {
                            // 手机号不是纯数字时，忽略手机号条件
                        }
                    }
                });
        
        User loginUser = userService.getOne(queryWrapper);
        
        if (loginUser != null) {
            // 登录成功，使用Sa-Token生成token
            StpUtil.login(loginUser.getId());
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
            
            Map<String, Object> userData = new HashMap<>();
            userData.put("id", loginUser.getId()); // 返回用户ID
            userData.put("account", loginUser.getAccount());
            userData.put("name", loginUser.getName());
            userData.put("phoneNumber", loginUser.getPhoneNumber());
            userData.put("avatar", loginUser.getAvatar());

    return ResponseEntity.ok(Map.of(
            "success", true,
                    "message", "登录成功",
                    "token", tokenInfo.getTokenValue(),
                    "user", userData
            ));
        } else {
            return ResponseEntity.ok(Map.of(
                    "success", false,
                    "message", "账号或密码错误"
            ));
        }
    } catch (Exception e) {
        return ResponseEntity.ok(Map.of(
                "success", false,
                "message", "登录失败: " + e.getMessage()
        ));
    }
}

@PostMapping("/logout")
public ResponseEntity<Map<String, Object>> logout() {
    try {
        // 登出当前用户
        StpUtil.logout();
        return ResponseEntity.ok(Map.of(
                "success", true,
                "message", "登出成功"
        ));
    } catch (Exception e) {
        return ResponseEntity.ok(Map.of(
                "success", false,
                "message", "登出失败: " + e.getMessage()
        ));
    }
}
    @PostMapping("/send-sms-code")
    public ResponseEntity<Map<String, Object>> sendSmsCode(@RequestBody Map<String, Object> body) {
        try {
            String phone = (String) body.get("phone");
            
            // 验证手机号格式
            if (phone == null || phone.trim().isEmpty()) {
                return ResponseEntity.ok(Map.of(
                        "success", false,
                        "message", "手机号不能为空"
                ));
            }
            
            // 简单的手机号格式验证
            if (!phone.matches("^1[3-9]\\d{9}$")) {
                return ResponseEntity.ok(Map.of(
                        "success", false,
                        "message", "请输入有效的手机号"
                ));
            }
            
            // 生成6位随机验证码
            int validCode = (int) (Math.random() * 900000) + 100000;
            
            // 这里应该调用短信服务发送验证码，现在只是模拟
            System.out.println("发送验证码到手机号: " + phone + ", 验证码: " + validCode);
            
      return ResponseEntity.ok(Map.of(
            "success", true,
                    "data", validCode, // 开发环境返回验证码，生产环境不应该返回
                    "message", "验证码已发送"
            ));
        } catch (Exception e) {
            return ResponseEntity.ok(Map.of(
                    "success", false,
                    "message", "验证码发送失败: " + e.getMessage()
            ));
        }
    }
}
